<template>
    <div class="chooser-component">
        <ul class="chooser-list">
            <li v-for="(item,index) in selections" :key="index" @click="changeSelection(index)"
            :title="item.label" :class="{active:checkActive(index)}" >{{item.label}}</li><!--checkActive()方法 -->
        </ul>
    </div>
</template>
<script>
import _ from 'lodash'
export default {
    props:{
        selections:{
            type:Array,
            default:[{
                label:'test',
                value:0
            }]
        }
    },
    data(){
        return{
            nowIndexes:[0]//将下标存在数组中
        }
    },
    methods:{
        changeSelection(index){
            console.log('当前选择的index： '+index);
            if(this.nowIndexes.indexOf(index) === -1){ //如果要检索的字符串值没有出现，则该方法返回 -1
                this.nowIndexes.push(index); //数组方法push()而不是push[]
            }else{
                //如果存在剔除重复
                /**
                 * var objA = {"name": "colin", "car": "suzuki", "age": 17}; 
                 * objA.remove(['car', 'age']); //通过key值筛选不存在滴
                 * objA; // {"name": "colin"}
                 */
                this.nowIndexes = _.remove(this.nowIndexes,idx => {
                    console.log('筛选之前的数组:' + this.nowIndexes);
                    console.log('筛选idx的值',idx);
                    return idx !== index;
                })
                 console.log('筛选之后的数组:'+ this.nowIndexes);
            }
                let nowObjArray = _.map(this.nowIndexes,idx =>{
                    console.log(this.nowIndexes);
                    return this.selections[idx];
                })

            //传递给父类
            console.log('传递到父类的数组 ',nowObjArray);
            this.$emit('on-change',nowObjArray);//此次使用let的局部定义，不可以传递this.nowObjArray
        },
        checkActive(index){
            return  this.nowIndexes.indexOf(index) !== -1 ; //检索搜到的数组值
        }
    }
}
</script>
<style scoped>
.chooser-component{position:relative;display:inline-block}
.chooser-list li{display:inline-block;border:1px solid #e3e3e3;height:25px;line-height:25px;padding:0 8px;margin-right:5px;border-radius:3px;text-align:center;cursor:pointer}
.chooser-list li.active{border-color:#4fc08d;background:#4fc08d;color:#fff}
</style>
